package com.ruoyi.lh.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.utils.CacheUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.security.Md5Utils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.lh.domain.Machine;
import com.ruoyi.lh.domain.Software;
import com.ruoyi.lh.mapper.MachineMapper;
import com.ruoyi.lh.mapper.SoftwareMapper;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.system.service.ISysDictTypeService;
import com.ruoyi.web.controller.dto.CheckUpdateParams;
import com.ruoyi.web.controller.dto.CheckUpdateResponse;
import com.ruoyi.web.controller.dto.LoginBackDto;
import com.ruoyi.web.controller.dto.LoginParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.lh.mapper.UserMapper;
import com.ruoyi.lh.domain.User;
import com.ruoyi.lh.service.IUserService;
import com.ruoyi.common.core.text.Convert;

/**
 * 更新用户Service业务层处理
 *
 * @author LH
 * @date 2023-08-28
 */
@Service
public class UserServiceImpl implements IUserService
{

    private final static String CACHE_NAME = "lh-user";
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SoftwareMapper softwareMapper;

    @Autowired
    private MachineMapper machineMapper;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;

    /**
     * 查询更新用户
     *
     * @param id 更新用户主键
     * @return 更新用户
     */
    @Override
    public User selectUserById(Long id)
    {
        return userMapper.selectUserById(id);
    }

    /**
     * 查询更新用户列表
     *
     * @param user 更新用户
     * @return 更新用户
     */
    @Override
    public List<User> selectUserList(User user)
    {
        return userMapper.selectUserList(user);
    }

    /**
     * 新增更新用户
     *
     * @param user 更新用户
     * @return 结果
     */
    @Override
    public int insertUser(User user)
    {
        return userMapper.insertUser(user);
    }

    /**
     * 修改更新用户
     *
     * @param user 更新用户
     * @return 结果
     */
    @Override
    public int updateUser(User user)
    {
        return userMapper.updateUser(user);
    }

    /**
     * 批量删除更新用户
     *
     * @param ids 需要删除的更新用户主键
     * @return 结果
     */
    @Override
    public int deleteUserByIds(String ids)
    {
        return userMapper.deleteUserByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除更新用户信息
     *
     * @param id 更新用户主键
     * @return 结果
     */
    @Override
    public int deleteUserById(Long id)
    {
        return userMapper.deleteUserById(id);
    }

    @Override
    public AjaxResult login(LoginParams loginParams) {
        List<User> users = userMapper.selectUserList(new User());
        if(null == users || users.isEmpty()) {
            return new AjaxResult(AjaxResult.Type.ERROR, "系统未创建用户!");
        }
        User user = users.get(0);
        LoginBackDto loginBackDto = null;
        if(user.getPassword().equalsIgnoreCase(loginParams.getM_ucUserPwr())) {
            String sessionJsonStr = (String) CacheUtils.get(CACHE_NAME, CACHE_NAME);
            if(StringUtils.isEmpty(sessionJsonStr)) {
                Date date = new Date();
//                String linkId = UUID.randomUUID(false).toString(false);
                String linkId = java.util.UUID.randomUUID().toString().replaceAll("-", "").substring(0,16);//生成16位的uuid,tcp协议需要
                String holdMinus = "1800";
                loginBackDto = new LoginBackDto(date, holdMinus, linkId);
                CacheUtils.put(CACHE_NAME, CACHE_NAME, JSON.toJSONString(loginBackDto));
            } else {
                loginBackDto = JSON.parseObject(sessionJsonStr, LoginBackDto.class);
            }
            return new AjaxResult(AjaxResult.Type.SUCCESS, "登录成功", loginBackDto);
        } else {
            return new AjaxResult(AjaxResult.Type.ERROR, "密码错误!");
        }

    }

    @Override
    public AjaxResult logout(String logout) {
        JSONObject jsonObject = JSON.parseObject(logout);
        String connectId = jsonObject.getString("m_ucConnectId");
        String sessionJsonStr = (String) CacheUtils.get(CACHE_NAME, CACHE_NAME);
        if(StringUtils.isNotEmpty(sessionJsonStr)) {
            LoginBackDto loginBackDto = JSON.parseObject(sessionJsonStr, LoginBackDto.class);
            if(loginBackDto.getM_ucConnectId().equals(connectId)) {
                CacheUtils.remove(CACHE_NAME, CACHE_NAME);
                return new AjaxResult(AjaxResult.Type.SUCCESS, "登出成功");
            } else {
                return new AjaxResult(AjaxResult.Type.ERROR, "连接id不一致");
            }
        } else {
            return new AjaxResult(AjaxResult.Type.SUCCESS, "登出成功");
        }
    }

  @Override
  public AjaxResult checkUpdate(CheckUpdateParams checkUpdateParams) {
    List<Software> softwareList = softwareMapper.selectSoftware(checkUpdateParams);
    if (softwareList != null && !softwareList.isEmpty()) {
      Optional<Software> min =
          softwareList.stream()
              .filter(Objects::nonNull)
              .filter(s -> s.getSoftwareVersion() != null)
              .min(Comparator.comparing(Software::getSoftwareVersion));
      Software software = min.get();
      String prefix = "";
      if (StringUtils.isNotEmpty(software.getUpdateFile())) {
        prefix = software.getUpdateFile().substring(software.getUpdateFile().lastIndexOf(".") + 1);
      }
      try{
          if (StringUtils.isNotEmpty(checkUpdateParams.getM_uiSoftDevSN())) {
              Machine machine = new Machine();
              machine.setSn(checkUpdateParams.getM_uiSoftDevSN());
              List<Machine> machineList = machineMapper.selectMachineList(machine);
              //查询支持软件版本的 字典数据
              List<SysDictData> softwareVersionList = iSysDictTypeService.selectDictDataByType("lh_software_version");
              List<String> dictValueList = softwareVersionList.stream().map(SysDictData::getDictValue).collect(Collectors.toList());

              String m_ucCurSV = checkUpdateParams.getM_ucCurSV();
              if (!machineList.get(0).getIsAcceptUpdate().equals("0") || !machineList.get(0).getStatus().equals("0")  || (StringUtils.isNotEmpty(m_ucCurSV) && !dictValueList.contains(m_ucCurSV))) {
                  return new AjaxResult(
                          AjaxResult.Type.SUCCESS,
                          "当前无需更新",
                          new CheckUpdateResponse("0", null,null, null, null, null, null, null, null));
              }
              if(software.getUpdateStrategy().equals("1")) {
                  if(!software.getReleaseArea().contains(machineList.get(0).getReleaseArea())) {
                      return new AjaxResult(
                              AjaxResult.Type.SUCCESS,
                              "当前无需更新",
                              new CheckUpdateResponse("0",null,null, null, null, null, null, null, null));
                  }
              }
          }
      } catch(Exception e) {
          return new AjaxResult(
                  AjaxResult.Type.SUCCESS,
                  "当前无需更新",
                  new CheckUpdateResponse("0", null, null, null, null, null, null, null,null));
      }

      return new AjaxResult(
          AjaxResult.Type.SUCCESS,
          "需要更新",
          new CheckUpdateResponse(
              "1",
              String.valueOf(software.getId()),
              software.getSoftwareName(),
              software.getSoftwareVersion(),
              prefix,
//              FileUtils.getNameNotSuffix(software.getUpdateFile()),
              FileUtils.getName(software.getUpdateFile()),
              software.getMd5(),
              software.getUpdateDes(),software.getFileSize())
      );
    }
    return new AjaxResult(
        AjaxResult.Type.SUCCESS,
        "当前无需更新",
        new CheckUpdateResponse("0", null, null, null, null, null, null, null, null));
  }
}
